<script setup lang="ts">
import { RefreshRight, RefreshLeft, Plus, Tickets } from '@element-plus/icons-vue'
import { inject, onMounted, reactive, ref } from 'vue';
import { ResponseStatus, type IdentityHttpService, type Role} from '../service/identity-http.service';
import DefaultAvatar from '@/area/common/components/DefaultAvatar.vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

var httpService = inject<IdentityHttpService>('IdentityHttpService');

defineEmits<{
  (e: 'detailClick', id: number) : void
}>();

onMounted(() => {
  loadRoleList();
});

//#region ---- Table above start ----
const queryString = ref('');
const roleList = ref<Role[]>();//从后台加载的数据
const roleListSearchResult = ref();//筛选后有文字高亮的数据
const roleListLoading = ref(false);

function loadRoleList() {
  roleListLoading.value = true;
  httpService?.apiRoleGetAll().then(result => {
    roleList.value = result;
    searchRole();
    roleListLoading.value = false;
  });
}

function searchRole() {
  let result = roleList.value?.filter(it => it.name?.indexOf(queryString.value) != -1);
  roleListSearchResult.value = JSON.parse(JSON.stringify(result));
  if(queryString.value != '') {
    roleListSearchResult.value = roleListSearchResult.value?.map((it: any) => {
      it.displayName = it.name?.replaceAll(queryString.value, `<span class="search-highlight">${queryString.value}</span>`);
      return it;
    });
  } else {
    roleListSearchResult.value = roleListSearchResult.value?.map((it: any) => {
      it.displayName = it.name;
      return it;
    });
  }
}
//#endregion ---- Table above end ----

//#region ----Create role form start----
//Dialog part
const createRoleDialogVisable = ref(false);
function showCreateRoleDialog() {
  clearCreateRoleForm(ruleFormRef.value);
  createRoleDialogVisable.value = true;
}

//Form part
const ruleFormRef = ref<FormInstance>();
const roleFormData = reactive({
  name: '',
  description: '',
  appName: ''
});
const roleFormRules = reactive<FormRules>({
  name: [
    { required: true, message: '请填写用户名', trigger: 'change' }, 
    { max: 20, message: '用户名不能超过20个字符', trigger: 'change' }, 
  ],
  appName: [{ required: true, message: '请选择系统名', trigger: 'change' }]
});

function clearCreateRoleForm(formEl: FormInstance | undefined) {
  formEl?.resetFields();
  roleFormData.description = '';
}

const createButtonLoading = ref(false);
function createRole(formEl: FormInstance | undefined) {
  formEl?.validate((isValid) => {
    if(!isValid) return;

    createButtonLoading.value = true;
    httpService?.apiRoleCreate(roleFormData.name, roleFormData.appName, roleFormData.description)
    .then(result => {
      createButtonLoading.value = false;
      if (result.status == ResponseStatus.Success) {
        loadRoleList();
        ElMessage({ type: 'success', message: result.message });
        createRoleDialogVisable.value = false;
      } else {
        ElMessage({ type: 'warning', message: result.message });
      }
    });
  });
}
//#endregion ----Create role form end----
</script>

<template>
<div class="common-shadow0 common-toolbar">
  <el-button :icon="RefreshRight" @click="loadRoleList()">刷新</el-button>
  <el-button :icon="Plus" @click="showCreateRoleDialog()">新建角色</el-button>
  <div style="display: inline;flex-grow: 1;"></div>
  <el-input style="width: 220px;" placeholder="Search" v-model="queryString" @input="searchRole()" />
</div>
<el-table class="common-shadow0 common-table" style="margin-top: 12px;" 
  :data="roleListSearchResult" v-loading="roleListLoading">
  <el-table-column label="" width="60">
    <template #default="scope">
      <DefaultAvatar :name="scope.row.name"/>
    </template>
  </el-table-column>
  <el-table-column prop="name" label="角色名">
    <template #default="scope">
      <div v-html="scope.row.displayName"></div>
    </template>
  </el-table-column>
  <el-table-column prop="description" label="描述" />
  <el-table-column prop="appName" label="所属系统" />
  <el-table-column label="" width="120">
    <template #default="scope">
      <el-button :icon="Tickets" type="primary" text @click="$emit('detailClick', scope.row.id)">详情</el-button>
    </template>
  </el-table-column>
</el-table>

<el-dialog title="新建角色" v-model="createRoleDialogVisable" width="460px">
  <el-form label-position="right" label-width="72px" :model="roleFormData" style="max-width: 460px" 
    ref="ruleFormRef" :rules="roleFormRules" >
    <el-form-item label="角色名" prop="name">
      <el-input v-model="roleFormData.name" />
    </el-form-item>
    <el-form-item label="描述" prop="nadescriptionme">
      <el-input v-model="roleFormData.description" />
    </el-form-item>
    <el-form-item label="系统名" prop="appName">
      <el-select v-model="roleFormData.appName" placeholder="Select" style="width: 100%;">
        <el-option key="Identity" label="Identity" value="Identity"></el-option>
        <el-option key="DevloperNote" label="DevloperNote" value="DevloperNote"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <div style="text-align: right;">
    <el-button :icon="RefreshLeft" @click="clearCreateRoleForm(ruleFormRef)">清空</el-button>
    <el-button type="primary" :icon="Plus" @click="createRole(ruleFormRef)" :loading="createButtonLoading">新建</el-button>
  </div>
</el-dialog>
</template>

<style lang="scss">
@use '../../../assets/variable.scss' as variable;
@use '../../../assets/common.scss';
.input-box {
  margin-bottom: 8px;

  span {
    min-width: 60px;
    white-space: nowrap;
  }
}

.search-highlight {
  color: variable.$orange0;
}
</style>